﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Depart;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class DepartController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DepartController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有科室信息
        /// </summary>
        /// <param name="branchName">分院名称(小写拼音),为空时表示所有分院</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll(string branchName = "")
        {
            var branchNo = DepartExtensions.ToBranchNo(branchName);
            var departs = _ctx.Depart.Where(x => x.RecStatus == 1);
            if (!string.IsNullOrEmpty(branchNo))
            {
                departs = departs.Where(x => x.BranchNo == branchNo);
            }

            var departsList = departs.OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

            return new GetAllResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Departs = departsList.Select(x => new GetAllResponse.Depart
                {
                    BranchName = DepartExtensions.ToBranchName(x.BranchNo),
                    DepartId = x.DeptId,
                    DepartName = x.DeptName
                }).ToList()
            };
        }

        /// <summary>
        /// 根据科室院内编号获取科室信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetByDeptId")]
        public GetByDeptIdResponse GetByDeptId(string deptId)
        {
            var depart = _ctx.Depart.FirstOrDefault(x => x.DeptId == deptId);
            if (depart == null)
            {
                return new GetByDeptIdResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到科室",
                };
            }

            var doctors = _ctx.Doctor.Where(x => x.RecStatus == 1 && x.DeptId == deptId)
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return new GetByDeptIdResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Name = depart.DeptName,
                Position = depart.Loc,
                Desc = string.IsNullOrEmpty(depart.Desc) ? "暂无介绍" : depart.Desc,
                Drs = doctors.Select(x => new GetByDeptIdResponse.Dr
                {
                    DoctorId = x.DoctorId,
                    DeptId = x.DeptId,
                    Name = x.DoctorName,
                    Sex = DoctorExtensions.ToZhSex(x.Gender),
                    Title = x.Title
                }).ToList()
            };
        }

        /// <summary>
        /// 搜索科室或医生
        /// </summary>
        /// <param name="keyword">科室或医生的名称，包含关系</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SearchDepartOrDr")]
        public SearchDepartOrDrResponse SearchDepartOrDr(string keyword)
        {
            var departs = _ctx.Depart.Where(x => x.RecStatus == 1 && x.DeptName.Contains(keyword))
                .OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

            var doctors = _ctx.Doctor.Where(x => x.RecStatus == 1 && x.DoctorName.Contains(keyword))
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return new SearchDepartOrDrResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Departs = departs.Select(x => new SearchDepartOrDrResponse.Depart
                {
                    DepartId = x.DeptId,
                    DepartName = x.DeptName
                }).ToList(),
                Drs = doctors.Select(x => new SearchDepartOrDrResponse.Dr
                {
                    DepartId = x.DeptId,
                    DepartName = x.DepartName,
                    DrId = x.DoctorId,
                    DrName = x.DoctorName,
                    Sex = DoctorExtensions.ToZhSex(x.Gender),
                    Title = x.Title
                }).ToList()
            };
        }

        /// <summary>
        /// 获取排班信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <param name="doctorId">医生院内编号，为空表示查询科室内所有医生</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetTimeSlices")]
        public GetTimeSlicesResponse GetTimeSlices(string deptId, string doctorId)
        {
            var res = new GetTimeSlicesResponse();
            res.DefaultSelectedDay = "无剩余号源";
            res.Today = DateTime.Now.ToString("yyyy-MM-dd");
            res.RegDays = new List<GetTimeSlicesResponse.ScheduleDay>();
            for (int i = 0; i < 8; i++)
            {
                res.RegDays.Add(new GetTimeSlicesResponse.ScheduleDay
                {
                    Date = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    IsFull = true,
                    TimeSlices = new List<GetTimeSlicesResponse.TimeSlice>()
                });
            }

            // 获取排班
            var request = new GetScheduleInfoRequest();
            request.DeptId = deptId;
            request.DoctorId = doctorId;
            request.BeginDate = DateTime.Now.ToString("yyyy-MM-dd");
            request.EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");

            GetScheduleInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetScheduleInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetScheduleInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "1";
                res.ResultMsg = "获取排班超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "2";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            var scheduleInfos = response.ScheduleList;

            foreach (var scheduleInfo in scheduleInfos)
            {
                var scheduleDay = res.RegDays.First(x => x.Date == scheduleInfo.RegDate);
                if (scheduleInfo.TotalCount == "不限号" || scheduleInfo.LeaveCount.ToInt32OrDefault() > 0)
                {
                    scheduleDay.IsFull = false;
                    if (res.DefaultSelectedDay == "无剩余号源")
                    {
                        res.DefaultSelectedDay = scheduleInfo.RegDate;
                    }
                }

                scheduleDay.TimeSlices.Add(new GetTimeSlicesResponse.TimeSlice
                {
                    ScheduleItemCode = scheduleInfo.ScheduleItemCode,
                    DeptId = scheduleInfo.DeptId,
                    DeptName = scheduleInfo.DeptName,
                    DoctorId = scheduleInfo.DoctorId,
                    DoctorName = scheduleInfo.DoctorName,
                    Title = scheduleInfo.Title,
                    RegType = scheduleInfo.RegType,
                    SliceName = scheduleInfo.TimeSlice,
                    SliceStartTime = scheduleInfo.StartTime,
                    SliceEndTime = scheduleInfo.EndTime,
                    LeaveCount = scheduleInfo.LeaveCount.ToInt32OrDefault() < 0 ? 0 : scheduleInfo.LeaveCount.ToInt32OrDefault(),
                    TotalCount = scheduleInfo.TotalCount.ToInt32OrDefault(),
                    HasTimePoint = scheduleInfo.IsTimeFlag == "1",
                    RegFee = 0,
                    TreatFee = scheduleInfo.TreatFee.ToDecimalOrDefault(),
                    OtherFee = scheduleInfo.OtherFee.ToDecimalOrDefault(),
                    TotalFee = scheduleInfo.Fee.ToDecimalOrDefault(),
                });
            }

            res.ResultCode = "0";
            res.ResultMsg = "";
            return res;
        }
    }
}
